<template>
	<zh-sheet :round="props.round" :margin="props.margin" :transprent="props.transprent" :padding="[0, 0]">
		<view class="content">
			<view class="container-content">
				<!-- 日期列表 -->
				<scroll-view class="scroll-view_H b-t b-b" scroll-x>
					<block v-for="(item, index) in dateArr" :key="index">
						<view class="flex-box" @click="selectDateEvent(index, item)">
							<zh-sheet class="date-box" :margin="[0, 0]" :padding="[0, 0]">
								<zh-text class="mb-10 flex-row-center-center"
									:class="index == dateActive ? 'fontw' : ''"
									:color="index == dateActive ? _selectedTabColor : '#333'">{{
                  item.week
                }}</zh-text>
								<zh-text
									:color="index == dateActive ? _selectedTabColor : '#333'">{{ item.date }}</zh-text>
							</zh-sheet>
							<zh-divider :margin="[10, 20]" :border="2"
								:color="index == dateActive ? _selectedTabColor : '#e5e5e5'" realColor></zh-divider>
						</view>
					</block>
				</scroll-view>

				<!-- 预约时间段 -->
				<scroll-view scroll-y style="height: 800rpx" :scroll-top="topValue" @scroll="scroll">
					<view class="time-box" v-if="isQuantum">
						<zh-row v-if="timeArr && timeArr.length > 0" :width="props.width" :margin="[0, 0]" :column="3"
							justify="start" align="center">
							<block v-for="(item, _index) in timeArr" :key="_index">
								<zh-col :height="props.itemHeight" v-if="item.show" :margin="[10, 0, 10, 0]">
									<zh-sheet :height="props.itemHeight - 60" :border="1"
										:class="_index == timeActive ? 'text-weight-b' : ''"
										:color="getItemColor(item, _index)" @click="selectTimeEvent(_index, item)"
										:round="2" :text="getItemText(item, _index)" :margin="[0, 0]" :padding="[0, 20]"
										_class="flex-row-center-center">
										<zh-text class="mb-15" :fontSize="26"
											:color="item.isActive ? _selectedItemColor : ''">{{ item.begin }}~{{ item.end }}</zh-text>
										<zh-text :color="item.isActive ? _selectedItemColor : ''"
											:fontSize="26">{{ item.remarks }}</zh-text>
									</zh-sheet>
								</zh-col>
							</block>
						</zh-row>
						<zh-result v-if="!hasTime" :showBtn="false" title="今天已没有可预约的时间" subTitle="请选择其他日期"></zh-result>
					</view>
					<!-- 预约时间 -->
					<view class="time-box" v-else>
						<zh-row v-if="timeArr && timeArr.length > 0" :width="props.width" :gutter="10" :column="3"
							justify="start" align="center">
							<block v-for="(item, _index) in timeArr" :key="_index">
								<zh-col :height="props.itemHeight" v-if="item.show">
									<zh-sheet :height="props.itemHeight - 60" :border="1"
										:class="_index == timeActive ? 'text-weight-b' : ''"
										:color="getItemColor(item, _index)" @click="selectTimeEvent(_index, item)"
										:round="2" :text="getItemText(item, _index)" :margin="[0, 0]" :padding="[0, 20]"
										_class="flex-row-center-center">
										<zh-text class="mb-15" :fontSize="26"
											:color="item.isActive ? _selectedItemColor : ''">{{ item.time }}</zh-text>
										<zh-text :fontSize="26"
											:color="item.isActive ? _selectedItemColor : ''">{{ item.remarks }}</zh-text>
									</zh-sheet>
								</zh-col>
							</block>
						</zh-row>
						<zh-result v-if="!hasTime" :showBtn="false" title="今天已没有可预约的时间" subTitle="请选择其他日期"></zh-result>
					</view>
				</scroll-view>
			</view>
			<view class="bottom" v-if="!props.hideButton">
				<view class="show-time"> 预约时间：{{ orderDateTime.str }} </view>
				<zh-button form-type="submit" label="确认预约" @click="handleSubmit"> </zh-button>
			</view>
		</view>
	</zh-sheet>
</template>
<script lang="ts" setup>
	import { ref, watch, defineEmits, defineProps, nextTick } from 'vue';
	import { initData, initTime, currentTime } from './date.js';
	import systemConfigStore from '@/store/modules/systemConfigStore';
	const store = systemConfigStore();
	const props = defineProps({
		width: {
			type: [Number, String],
			default: 750,
		},
		itemHeight: {
			type: [Number, String],
			default: 180,
		},
		margin: {
			type: Array as PropType<Array<number>>,
			default: () => [0, 0],
		},
		round: {
			type: Number,
			default: 2,
		},
		padding: {
			type: Array as PropType<Array<number>>,
			default: () => [0, 0],
		},
		/**
		 * 是否跟随全局主题的变换而变换
		 */
		followTheme: {
			type: [Boolean, String],
			default: false,
		},
		/**
		 * 暗黑
		 */
		dark: {
			type: [Boolean, String],
			default: false,
		},
		//是否显示底部信息
		hideButton: {
			type: [Boolean],
			default: true,
		},
		modelValue: {
			type: [String],
			default: undefined,
		},
		endValue: {
			type: [String],
			default: undefined,
		},
		/**
		 * 是否跟随主题全局切换暗黑模式。
		 */
		followDark: {
			type: [Boolean, String],
			default: true,
		},
		//是否透明背景
		transprent: {
			type: Boolean,
			default: false,
		},
		//是否显示当前时间之前的时间
		showBeforTime: {
			type: Boolean,
			default: false,
		},
		//预约时间段
		isQuantum: {
			type: Boolean,
			default: true,
		},

		disableText: {
			//禁用显示的文本
			type: String,
			default: '休息中',
		},
		fullText: {
			//约满显示的文本
			type: String,
			default: '已约满',
		},
		undisableText: {
			//未禁用显示的文本
			type: String,
			default: '可预约',
		},
		timeInterval: {
			// 时间间隔，分钟为单位
			type: Number,
			default: 30,
		},
		max: {
			// 最大初始化天数
			type: Number,
			default: 7,
		},
		selectedTabColor: {
			// 日期栏选中的颜色
			type: String,
			default: 'primary',
		},
		selectedItemColor: {
			// 时间选中的颜色
			type: String,
			default: 'primary',
		},
		beginTime: {
			type: String,
			default: '08:00:00',
		},
		endTime: {
			type: String,
			default: '18:00:00',
		},
		disableTimeSlot: {
			// 预约开始和结束时间，来禁用时间段
			type: Array,
			default() {
				return [];
			},
		},
		fullTimeSlot: {
			// 预约开始和结束时间，显示预满时间段
			type: Array,
			default() {
				return [];
			},
		},
	});
	const emit = defineEmits(['change', 'update:modelValue', 'update:endValue', 'click']);
	const topValue = ref(0);
	let orderDateTime = ref<any>({ str: '请选择' }); // 选中时间
	let orderTimeArr = ref<any>({}); //多选的时间
	let dateArr = ref<any>([]); //日期数据
	let timeArr = ref<any>([]); //时间数据
	let nowDate = ref<string>(currentTime().date); // 当前日期
	let selectDate = ref<string>(currentTime().date); //选择的日期
	let dateActive = ref<number>(0); //选中的日期索引
	let timeActive = ref<number>(-1); //选中的时间索引
	let _beginValue = ref<string>(props.modelValue); //时间段开始时间
	let _endValue = ref<string>(props.endValue); //时间段结束时间
	let hasTime = ref(true);
	const getItemColor = (item, _index) => {
		if (item.disabled) {
			return 'white';
		}
		if (item.fulled) {
			return 'red';
		}
		return _index == timeActive.value ? _selectedItemColor.value : 'white';
	};
	const getItemText = (item, _index) => {
		if (item.disabled) {
			return true;
		}
		if (item.fulled) {
			return true;
		}
		return _index == timeActive.value ? true : false;
	};
	const _selectedTabColor = computed(() => {
		let color = props.selectedTabColor;
		if (props.followTheme && store.color) {
			color = store.color;
		}
		return color;
	});
	const _selectedItemColor = computed(() => {
		let color = props.selectedItemColor;
		if (props.followTheme && store.color) {
			color = store.color;
		}
		return color;
	});
	const initOnload = (flag) => {
		dateArr.value = initData(props.max); // 日期栏初始化
		timeArr.value = initTime(props.beginTime, props.endTime, props.timeInterval, props.isQuantum); //时间选项初始化
		if (flag && _beginValue.value) {
			let [date, time] = _beginValue.value.split(' ');
			selectDate.value = date;
			let index = dateArr.value.findIndex((item : any) => item.date === date);
			if (index >= 0) {
				dateActive.value = index;
			}
		}
		let count = 0;
		let i = 0;
		let timeFlag = false;
		timeArr.value.forEach((item : any) => {
			// 根据传入的参数判断是否选中

			item.remarks = props.undisableText;
			// 时间段
			if (props.isQuantum) {
				if (_beginValue.value && _endValue.value) {
					const cur_be_time = `${selectDate.value} ${item.begin}:00`;
					const cur_end_time = `${selectDate.value} ${item.end}:00`;
					if (_beginValue.value <= cur_be_time && cur_end_time <= _endValue.value) {
						timeFlag = true;
						timeActive.value = i;
						item.isActive = true;
						item.remarks = '当前选择';
						if (flag) {
							if (i > 1) {
								topValue.value = (i - 2) * 20;
							}
							orderDateTime.value = {
								str: `${selectDate.value} ${item.begin}~${item.end}`,
								begin: _beginValue.value,
								end: _endValue.value,
							};
						}
					}
				}
				const cur_be_time = `${selectDate.value} ${item.begin}:00`;
				const cur_end_time = `${selectDate.value} ${item.end}:00`;
				for (let time of props.disableTimeSlot) {
					const begin_time : any = time[0];
					const end_time : any = time[1];
					if (begin_time && end_time && begin_time <= cur_be_time && cur_end_time <= end_time) {
						item.disabled = true;
						item.remarks = props.disableText;
					}
				}
				for (let time of props.fullTimeSlot) {
					const begin_time : any = time[0];
					const end_time : any = time[1];
					if (begin_time && end_time && begin_time <= cur_be_time && cur_end_time <= end_time) {
						item.fulled = true;
						item.remarks = props.fullText;
					}
				}
				if (selectDate.value == nowDate.value && currentTime().time > `${item.begin}:00`) {
					item.disabled = true;
					item.remarks = '时间已过';
					if (props.showBeforTime) {
						item.show = true;
						count++;
					} else {
						item.show = false;
					}
				} else {
					count++;
				}
			} else {
				const cur_be_time = `${selectDate.value} ${item.time}`;
				if (_beginValue.value && cur_be_time == _beginValue.value) {
					timeFlag = true;
					timeActive.value = i;
					item.isActive = true;
					item.remarks = '当前选择';
					if (flag) {
						orderDateTime.value = { str: `${selectDate.value} ${item.time}`, time: _beginValue.value };
						if (i > 1) {
							topValue.value = (i - 2) * 20;
						}
					}
				}
				//判断是当前这一天，选中时间小于当前时间则禁用
				if (selectDate.value == nowDate.value && currentTime().time > item.time) {
					item.fulled = true;
					item.remarks = props.fullText;
					if (props.showBeforTime) {
						item.show = true;
						count++;
					} else {
						item.show = false;
					}
				} else {
					count++;
				}
				const cur_time = `${selectDate.value} ${item.time}`;
				// 将已约满时间标识
				for (let time of props.fullTimeSlot) {
					if (time == cur_time) {
						item.fulled = true;
						item.remarks = props.fullText;
					}
				}

				// 禁用时间段

				for (let time of props.disableTimeSlot) {
					if (time == cur_time) {
						item.disabled = true;
						item.remarks = props.disableText;
					}
				}
			}
			i++;
		});
		if (count > 0) {
			hasTime.value = true;
		} else {
			hasTime.value = false;
		}
	};
	onMounted(() => {
		initOnload(true);
	});

	const scroll = (e) => {
		topValue.value = e.detail.scrollTop;
	};
	// 日期选择事件
	const selectDateEvent = (index : number, item : any) => {
		nextTick(() => {
			topValue.value = 0;
		});
		timeActive.value = -1;
		dateActive.value = index;
		selectDate.value = item.date;
		initOnload();
	};

	// 时间选择事件
	const selectTimeEvent = (index : number, item : any) => {
		if (item.disabled) return;
		if (props.isQuantum) {
			return handleSelectQuantum(index, item);
		}

		timeActive.value = index;
		orderDateTime.value = { time: `${selectDate.value} ${item.time}`, str: `${selectDate.value} ${item.time}` };
		emit('click', orderDateTime.value);
	};

	// 选择时间段

	const handleSelectQuantum = (index : number, item : any) => {
		if (item.disabled) return;

		timeActive.value = index;
		orderDateTime.value = {
			begin: `${selectDate.value} ${item.begin}:00`,
			end: `${selectDate.value} ${item.end}:00`,
			str: `${selectDate.value} ${item.begin}~${item.end}`,
		};
		emit('click', orderDateTime.value);
	};

	const handleSubmit = () => {
		emit('change', orderDateTime.value);
		if (props.isQuantum) {
			emit('update:modelValue', orderDateTime.value.begin);
			emit('update:endValue', orderDateTime.value.end);
		} else {
			emit('update:modelValue', orderDateTime.value.time);
		}
	};
	watch(
		() => props.appointTime,
		(val : any) => {
			if (val && val.length) {
				initOnload();
			}
		},
		{
			immediate: true,
			deep: true,
		}
	);
	watch(
		() => [props.modelValue, props.endValue],
		() => {
			_beginValue.value = props.modelValue;
			_endValue.value = props.endValue;
			initOnload(true);
		},
		{
			deep: true,
		}
	);
	defineExpose({
		orderDateTime,
	});
</script>

<style lang="scss" scoped>
	@import './pretty-times.scss';

	page {
		height: 100%;
	}

	.content {
		text-align: center;
		height: 100%;
	}

	/* 两个按钮 */
	.bottom {
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 0 20rpx;
		background-color: #fff;
	}

	.show-time {
		width: 70%;
		height: 50rpx;
		color: #505050;
		background-color: rgba(255, 255, 255, 1);
		font-size: 26rpx;
		line-height: 50rpx;
		text-align: center;
	}

	.fontw {
		font-weight: bold;
	}

	.borderb {
		border-bottom: 2px solid #fb4b5c;
	}
</style>